package com.token.wsset.soap;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 发送soap格式的xml请求
 * @author cjx
 */
public class SendSoap {
    private String errorCode = "";
    private String errorDetail = "";
    private Element returnItem = null;
    /**
     * 发送
     * @param url1
     * @throws Exception
     */
    public boolean httpPost(String url1,SoapXML body) throws Exception {
        String returnNodeName = body.getReturnNodeName();
        boolean isok = false;
        if(returnNodeName == null || "".equals(returnNodeName)){
            throw new Exception("返回方法名为空值！");
        }
        try {
            URL url = new URL(url1);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            String soapXml = body.getSoapXML();
            conn.setRequestProperty("Content-Length",String.valueOf(soapXml.length()));
            conn.setRequestProperty("Content-Type","text/xml;charset=UTF-8");
            conn.setRequestProperty("Accept-Encoding","gzip,deflate");
            conn.setRequestProperty("SOAPAction","");
            conn.setRequestMethod("POST");

            OutputStream os = conn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");
            osw.write(soapXml);
            osw.flush();
            osw.close();
//            System.out.println("conn.getResponseCode() = " + conn.getResponseCode());
            if(conn.getResponseCode() == 200){
                InputStream is = conn.getInputStream();
                openXmlDocument(is, returnNodeName);
                is.close();
            }else{
                throw new Exception(conn.getResponseMessage());
            }

            if(this.errorCode.equals("0")){
                isok = true;
            }
            conn.disconnect();
        } catch(IOException e){
            e.printStackTrace();
            throw new Exception("网络异常或请求超时");
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return isok;
    }


    /**
     * 从InputStream中读取Document对象
     * @param in
     */
    private void openXmlDocument(InputStream in,String returnNodeName) {
        SAXReader reader = new SAXReader();
        try {
            Document reqDoc = reader.read(in);
//            System.out.println("reader.toString() = " + reader.toString());
            Element root = reqDoc.getRootElement();
            Element body = root.element("Body");
//            System.out.println("body.asXML() = " + body.asXML());
            returnItem = body.element(returnNodeName);
            Element errorCode = returnItem.element("code");
            Element errorDetail = returnItem.element("message");
            this.errorCode = errorCode.getText();
            this.errorDetail = errorDetail.getText();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @return
     * @throws Exception
     */
    public String getReturnJsonString() throws Exception{
        if(this.returnItem == null){
            throw new Exception("returnItem=Null，没有返回值！");
        }

        Element tmp = this.returnItem.element("jsonString");
        String text = null;
        if(tmp != null){
            text = tmp.getText();
        }
        return text;
    }

    /**
     *
     * @return
     */
    public String getErrorCode() {
        return errorCode;
    }
    /**
     *
     * @return
     */
    public String getErrorDetail() {
        return errorDetail;
    }

}